//
//  CNCollectSelectController.m
//  CsdnPlus
//
//  Created by wxlan on 2019/8/9.
//  Copyright © 2019 CSDN. All rights reserved.
//

#import "CNCollectSelectController.h"
#import "CNCollectStatusViewModel.h"
#import "CNCreatNewFavoritesController.h"
#import "CNMineNewCollectModel.h"
#import <HWPanModal/HWPanModal.h>
#import <CNBaseTool/CNCategoryHeader.h>
#import <CNBaseViewTool/CNLoadingGifView.h>
#import <CNBaseViewTool/CNNoDataView.h>
#import <CNBaseViewTool/UIView+CNEmpty.h>
#import <CNBaseViewTool/CNRefreshGifHeader.h>
#import <CNBaseViewTool/CNViewConst.h>

#import <Masonry/Masonry.h>
@interface CNCollectSelectController ()<UITableViewDelegate, UITableViewDataSource,HWPanModalPresentable>
@property (nonatomic, strong) CNCollectStatusViewModel *viewModel;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CNLoadingGifView *loadingView;

@property (nonatomic, strong) CNNoDataView *noDataView;

@property (nonatomic, strong) CNNoDataView *noNetworkView;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, copy) NSString *source;
@property (nonatomic, strong) CNMineNewCollectModel *collectModel;
@end

@implementation CNCollectSelectController
- (instancetype)initWithCollectModel:(CNMineNewCollectModel *)collectModel{
    if (self = [super init]) {
        self.collectModel = collectModel;
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.theme_backgroundColor = pageBGColorPicker;
    // Do any additional setup after loading the view.
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(48);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(self.topView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.bottom.mas_equalTo(0);
        }
    }];
    [self refreshData:YES shouldShowTips:NO];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)dealloc{
    
}
#pragma mark -- 刷新数据
/** 暴露给外边的刷新方法 */
- (void)headerRefresh {
    [self.tableView.mj_header beginRefreshing];
}
- (void)refreshData:(BOOL)header shouldShowTips:(BOOL)showTip{
    [self.loadingView setHidden:self.viewModel.rowNumber];
    //占位图调用时机
    [self.tableView cn_startLoading];
    CNMineCollectContentModel *contentModel = (CNMineCollectContentModel *)self.collectModel.content;

    [self.viewModel checkFavoriteWithUrl:contentModel.url source:self.collectModel.Source completionHandle:^(NSError *error) {
        if (!error)
        {
            if (self.viewModel.code == 200)
            {
                //AF的回调 是在主线程中
                [self.tableView reloadData];
                [self.loadingView setHidden:YES];
                self.tableView.cn_emptyView = self.noDataView;
                [self hw_panModalSetNeedsLayoutUpdate];
            }
            else
            {
                [self.loadingView setHidden:YES];
                [self showErrorMsg:@"加载失败，请稍后再试"];
                
            }
            
        }else
        {
            [self showError:error];;
            [self.loadingView setHidden:YES];
            self.tableView.cn_emptyView = self.noNetworkView;
            
        }
        [self.tableView.mj_header endRefreshing];
        //占位图调用时机
        [self.tableView cn_endLoading];
    }];

}
#pragma mark -UITableviewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.viewModel.rowNumber;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"favoritecell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"favoritecell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentView.theme_backgroundColor = pageBGColorPicker;

        UILabel *collectTitleLabel = [[UILabel alloc] init];
        [cell.contentView addSubview:collectTitleLabel];
        [collectTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.top.mas_equalTo(12);
            make.height.mas_equalTo(20);
            
        }];
        
        //        collectTitleLabel.text = @"默认收藏夹";
        collectTitleLabel.theme_textColor = cellTitleTextColorPicker;
        collectTitleLabel.font = [UIFont systemFontOfSize:16];
        collectTitleLabel.tag = 10;
        UILabel *collectCountLabel = [[UILabel alloc] init];
        [cell.contentView addSubview:collectCountLabel];
        [collectCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(collectTitleLabel);
            make.top.equalTo(collectTitleLabel.mas_bottom).offset(8);
            make.height.mas_equalTo(16);
            
        }];
        
        //        collectCountLabel.text = @"0个内容";
        collectCountLabel.theme_textColor = cellDesTitleTextColorPicker;
        collectCountLabel.font = [UIFont systemFontOfSize:12];
        collectCountLabel.tag = 11;
        
        UIButton *favoriteButton = [[UIButton alloc] init];
        [cell.contentView addSubview:favoriteButton];
        [favoriteButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(60, 24));
            make.right.mas_equalTo(-16);
            make.centerY.equalTo(cell.contentView.mas_centerY);
        }];
        [favoriteButton setTitle:@"收藏" forState:UIControlStateNormal];
        [favoriteButton theme_setTitleColor:naviBGColorPicker forState:UIControlStateNormal];
        favoriteButton.titleLabel.font = [UIFont systemFontOfSize:14];
        favoriteButton.layer.theme_borderColor = focusButtonBoardColorPicker;
        favoriteButton.layer.cornerRadius = 5;
        favoriteButton.layer.borderWidth = 0.5;
        favoriteButton.tag = 12;
        
    }
    
    UILabel *collectTitleLabel = (UILabel *)[cell viewWithTag:10];
    UILabel *collectCountLabel = (UILabel *)[cell viewWithTag:11];
    collectTitleLabel.text = [self.viewModel collectFolderNameForRow:indexPath.row];
    collectCountLabel.text = [NSString stringWithFormat:@"%@ 个内容",@([self.viewModel collectFolderFavoriteNumForRow:indexPath.row])] ;
    UIButton *favoriteButton = (UIButton *)[cell viewWithTag:12];
    BOOL isFavorite = [self.viewModel collectFolderIsFavoritedForRow:indexPath.row];

    [favoriteButton setTitle:isFavorite?@"已收藏":@"收藏" forState:UIControlStateNormal];
    [favoriteButton theme_setTitleColor:isFavorite?isFavoriteButtonTitlePicker:naviBGColorPicker forState:UIControlStateNormal];
    favoriteButton.layer.theme_borderColor =isFavorite?isFavoriteButtonBoardColorPicker: focusButtonBoardColorPicker;

    @weakify(self)
    [favoriteButton bk_addEventHandler:^(id sender) {
        @strongify(self)
               if (isFavorite) {
                   [self delFavoriteWithRow:indexPath.row];
               }else{
                   [self addFavoriteWithRow:indexPath.row];
                   
               }
    } forControlEvents:(UIControlEventTouchUpInside)];
    return cell;
}
- (void)delFavoriteWithRow:(NSInteger)row{
    @weakify(self)
    [self.viewModel delFavoriteWithFavoritedId:[self.viewModel collectFolderFavoriteIdForRow:row] completionHandle:^(NSError *error) {
        @strongify(self)
        if (!error) {
            if (self.viewModel.code == 200)
            {
                
                
                if (self.favoriteResultBlock) {
                    self.favoriteResultBlock(YES,NO,@"取消收藏");
                }
                [self refreshData:YES shouldShowTips:NO];
            }
            else
            {
                if (self.favoriteResultBlock) {
                    self.favoriteResultBlock(NO,NO,self.viewModel.message?:@"取消收藏失败");
                }
                
            }
        }
        else
        {
            if (self.favoriteResultBlock) {
                self.favoriteResultBlock(NO,NO,error.userInfo[NSLocalizedDescriptionKey]?:@"取消收藏失败");
            }        }
    }];

}
- (void)addFavoriteWithRow:(NSInteger)row{
    @weakify(self)
    [self.viewModel addFavoriteWithFolderId:[self.viewModel collectFolderIdForRow:row] collectionModel:self.collectModel completionHandle:^(NSError *error) { 
        @strongify(self)
        if (!error) {
            if (self.viewModel.code == 200)
            {

                if (self.favoriteResultBlock) {
                    self.favoriteResultBlock(YES,YES,@"已收藏");
                    //保存收藏状态
                    [CNViewConst saveCollectionAction];
                }

                [self refreshData:YES shouldShowTips:NO];

            }
            else
            {
                if (self.favoriteResultBlock) {
                    self.favoriteResultBlock(NO,YES,self.viewModel.message?:@"收藏失败");
                }
            }
        }
        else
        {
            if (self.favoriteResultBlock) {
                self.favoriteResultBlock(NO,YES,error.userInfo[NSLocalizedDescriptionKey]?:@"收藏失败");
            }
        }
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 68;
}
#pragma mark -setter and getter
- (CNCollectStatusViewModel *)viewModel{
    if (_viewModel == nil) {
        _viewModel = [[CNCollectStatusViewModel alloc] init];
    }
    return _viewModel;
}
- (UIView *)topView{
    if (_topView == nil) {
        _topView = [[UIView alloc] init];
        _topView.theme_backgroundColor = pageBGColorPicker;
        
        PPButton *btn = [PPButton buttonWithType:UIButtonTypeCustom];
        [btn theme_setImage:naviCleanImage forState:UIControlStateNormal]; //设置自定义返回图片
        [btn theme_setImage:naviCleanImage forState:UIControlStateHighlighted]; //设置自定义返回图片
        [_topView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(16, 24));
            make.left.mas_equalTo(16);
            make.centerY.equalTo(self.topView.mas_centerY);
        }];
        btn.touchInsets = UIEdgeInsetsMake(-10, -20, -10, -20);
        @weakify(self);
        [btn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (self.presentationController) {
               [self dismissViewControllerAnimated:YES completion:nil];
            }
        } forControlEvents:UIControlEventTouchUpInside];
        
        
        UIButton *creatButton = [[UIButton alloc] init];
        [_topView addSubview:creatButton];
        [creatButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(112, 24));
            make.right.mas_equalTo(-16);
            make.centerY.equalTo(self.topView.mas_centerY);
        }];
        creatButton.layer.cornerRadius = 12;
        creatButton.theme_backgroundColor = newSearchBarBGPickerColor;
        
        [creatButton setTitle:@"+ 新建收藏夹" forState:UIControlStateNormal];
        [creatButton theme_setTitleColor:mainTextColorPicker forState:UIControlStateNormal];
        creatButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        [creatButton bk_addEventHandler:^(id sender) {
            CNCreatNewFavoritesController *vc = [[CNCreatNewFavoritesController alloc] init];
            vc.AddFolderBlock = ^(CNMineCollectFoldersModel * _Nonnull folderModel) {
                @strongify(self)
                
                [CSDNTool showAlert:@"创建成功" inView:self.fromViewController.view];
            };
            if (self.naviController ) {
                [self.naviController pushViewController:vc animated:YES];
                
            }else{
                [self.fromViewController.navigationController pushViewController:vc animated:YES];
            }
            if (self.presentationController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } forControlEvents:(UIControlEventTouchUpInside)];
   
  
        UIView *lineView = [[UIView alloc]init];
        lineView.theme_backgroundColor = myHeadLineBGColor;
        [_topView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.height.mas_equalTo(0.5);
        }];
        lineView.layer.zPosition = 10;

    }
    
    return _topView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView= [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        
        _tableView.theme_backgroundColor = pageBGColorPicker;
        
        //去掉分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
       
        
        
        @weakify(self);
        _tableView.mj_header = [CNRefreshGifHeader headerWithRefreshingBlock:^{
            @strongify(self);
            [self refreshData:YES shouldShowTips:YES];
        }];
        
        _tableView.cn_emptyView = self.noDataView;

        
        
    }
    return _tableView;
}

- (CNLoadingGifView *)loadingView{
    if(!_loadingView){
        _loadingView = [[CNLoadingGifView alloc]init];
        [self.view addSubview:_loadingView];
        [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    return _loadingView;
}

- (CNNoDataView *)noDataView{
    if (!_noDataView) {
        _noDataView = [CNNoDataView diyEmptyView];
    }
    if ([CNThemesManager isNight])
    {
        _noDataView.imageStr = @"noData_b";
    }
    else
    {
        _noDataView.imageStr = @"noData_w";
    }
    return _noDataView;
}
- (CNNoDataView *)noNetworkView{
    if (!_noNetworkView) {
        _noNetworkView = [CNNoDataView diyEmptyActionViewWithTarget:self action:@selector(headerRefresh)];
    }
    if ([CNThemesManager isNight])
    {
        _noNetworkView.imageStr = @"noNetwork_b";
    }
    else
    {
        _noNetworkView.imageStr = @"noNetwork_w";
    }
    return _noNetworkView;
}



- (CGFloat)topOffset {
    return 0;
}

- (PanModalHeight)longFormHeight {
    return PanModalHeightMake(PanModalHeightTypeMaxTopInset, kScreenHeight * 0.5);
}

- (BOOL)allowScreenEdgeInteractive {
    return NO;
}

- (BOOL)showDragIndicator {
    return NO;
}

- (BOOL)isPanScrollEnabled{
    return NO;
}
/**
 * 是否允许drag操作dismiss presented Controller
 * Default is YES
 */
- (BOOL)allowsDragToDismiss{
    return NO;
}

- (BOOL)shouldRoundTopCorners{
    return NO;
}

- (BOOL)shouldRespondToPanModalGestureRecognizer:(nonnull UIPanGestureRecognizer *)panGestureRecognizer{
    return NO;
}

@end
